/**
 * 联通每日签到领取1G流量
 */
const $ = Env("联通签到领流量");
const moment = require('moment');
var crypto = require('crypto');
const axios = require('axios');
const notify = $.isNode() ? require('./sendNotify') : '';
//手机号
let mobile = process.env.UNICOM_MOBILE ? process.env.UNICOM_MOBILE : '';
//服务密码
let password = process.env.UNICOM_PASSWORD ? process.env.UNICOM_PASSWORD : '';
//联通营业厅appId
let appId = process.env.UNICOM_APP_ID ? process.env.UNICOM_APP_ID : '';
//是否自动激活流量包
let isActive = process.env.UMICOM_IS_ACTIVE ? process.env.UMICOM_IS_ACTIVE : false;

const publicKey = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDc+CZK9bBA9IU+gZUOc6
FUGu7yO9WpTNB0PzmgFBh96Mg1WrovD1oqZ+eIF4LjvxKXGOdI79JRdve9
NPhQo07+uqGQgE4imwNnRx7PFtCRryiIEcUoavuNtuRVoBAm6qdB0Srctg
aqGfLgKvZHOnwTjyNqjBUxzMeQlEC2czEMSwIDAQAB
-----END PUBLIC KEY-----`.toString('ascii');

!(async () => {
    if (mobile == "" || password == "" || appId == "") {
        console.log('【提示】手机号、服务密码、联通营业厅appId都不能为空\n');
        return;
    }
    $.msg = "";
    $.isLogin = true;
    $.cookie = "";
    await login();
    if (!$.isLogin) {
        console.log('cookie已失效');
        if ($.isNode()) await notify.sendNotify($.name, 'cookie已失效', { index: 1 });
        return;
    }
    await $.wait(1000);
    await daySign();
    await $.wait(2000);
    await mygiftbag();
    if ($.isNode()) {
        console.log($.msg);
        notify.sendNotify($.name, $.msg, { index: 1 });
    }
})().catch((e) => {
    $.log('', `❌失败! 原因: ${e}!`, '');
}).finally(() => {
    $.done();
});

//生成deviceId
function generateMixed(n) {
    var chars = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
    let res = "";
    for (var i = 0; i < n; i++) {
        var id = Math.floor(Math.random() * 9);
        res += chars[id];
    }
    return res;
}

// 创建加密算法
function rsapublicKeyEncode(data) {
    let crypted = crypto.publicEncrypt({
        key: publicKey,
        padding: crypto.constants.RSA_PKCS1_PADDING
    }, Buffer.from(data + '')).toString('base64');
    return crypted;
}

//参数处理
function transParams(data) {
    let params = new URLSearchParams();
    for (let item in data) {
        params.append(item, data['' + item + '']);
    }
    return params;
}

//登录
async function login() {
    let deviceId = generateMixed(15);
    let params = {
        'appId': appId,
        'deviceBrand': 'Xiaomi',
        'deviceCode': deviceId, // IMEI
        'deviceId': deviceId,
        'deviceModel': 'Mi 10',
        'deviceOS': '',
        'isRemberPwd': 'true',
        'keyVersion': '',
        'mobile': rsapublicKeyEncode(mobile),
        'netWay': 'Wifi',
        'password': rsapublicKeyEncode(password),
        'pip': '36.33.244.15',
        'provinceChanel': 'general',
        'simCount': '0',
        'timestamp': moment().format('YYYYMMDDHHmmss'),
        'version': 'android@8.0805',
        'yw_code': ''
    };
    const { data, headers } = await axios.request({
        baseURL: 'https://m.client.10010.com',
        headers: {
            "User-Agent": "Mozilla/5.0 (Linux; Android 11; Mi 10 Build/RKQ1.200826.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/92.0.4515.131 Mobile Safari/537.36; unicom{version:android@8.0805,desmobile:13215626459};devicetype{deviceBrand:Xiaomi,deviceModel:Mi 10};{yw_code:}",
            "Referer": "https://m.client.10010.com",
            "Origin": "https://m.client.10010.com"
        },
        url: `/mobileService/login.htm`,
        method: 'post',
        data: transParams(params)
    });
    if (data.code == '0') {
        $.isLogin = true;
        $.cookie = 'token_online=' + data.token_online + '; appId=' + data.appId + ';' + headers['set-cookie'];
        $.cookie = $.cookie.replace(RegExp('Domain=10010.com; Path=/,', 'g'), '').replace(RegExp('Domain=.10010.com; Path=/,', 'g'), '');
    } else {
        console.log('登陆失败:' + data.dsc)
    }
}

//每日签到    
async function daySign() {
    var option = {
        url: 'https://act.10010.com/SigninApp/signin/daySign',
        headers: {
            "Origin": "https://img.client.10010.com",
            "Cookie": $.cookie,
            "Connection": "keep-alive",
            "Content-Type": "application\/x-www-form-urlencoded",
            "Accept": "application/json, text/plain, */*",
            "Host": "act.10010.com",
            "User-Agent": "Mozilla/5.0 (Linux; Android 11; Mi 10 Build/RKQ1.200826.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/92.0.4515.131 Mobile Safari/537.36; unicom{version:android@8.0805,desmobile:13215626459};devicetype{deviceBrand:Xiaomi,deviceModel:Mi 10};{yw_code:}",
            "Referer": "https://img.client.10010.com/SigininApp/index.html",
            "Accept-Language": "zh-cn"
        }
    };
    return new Promise(resolve => {
        $.post(option, async (err, resp, data) => {
            try {
                if (err) {
                    console.log(`${$.name} API请求失败，请检查网路重试`);
                    console.log(`${JSON.stringify(err)}`)
                } else {
                    data = JSON.parse(data);
                    if (data.status == "0000") {
                        $.msg += `【签到】${data.data.giftsDesc}\n`;
                    } else {
                        $.msg += `【签到】${data.msg}\n`;
                    }
                }
            } catch (e) {
                $.logErr(e, resp)
            } finally {
                resolve(data);
            }
        })
    });
}

//查询流量礼包
async function mygiftbag() {
    return new Promise(resolve => {
        try {
            var option = {
                url: 'https://m.client.10010.com:443/myPrizeForActivity/mygiftbag.htm',
                headers: {
                    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                    "Origin": "https://m.client.10010.com",
                    //"Accept-Encoding": "gzip, deflate, br",
                    "Cookie": $.cookie,
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Host": "m.client.10010.com",
                    "Connection": "keep-alive",
                    "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 unicom{version:iphone_c@8.0200}{systemVersion:dis}{yw_code:}",
                    "Content-Length": "142",
                    "Accept-Language": "zh-cn"
                },
                body: 'typeScreenCondition=2&category=FFLOWPACKET&pageSign=1&CALLBACKURL=https%3A%2F%2Fm.client.10010.com%2FmyPrizeForActivity%2Fquerywinninglist.htm'
            };

            $.post(option, async (err, resp, data) => {
                try {
                    if (err) {
                        console.log(`${$.name} API请求失败，请检查网路重试`);
                        console.log(`${JSON.stringify(err)}`)
                    } else {
                        //******解析HTML信息***********
                        var s = data.indexOf('id="prizeRecord"');
                        var e = data.indexOf('class="tanceng"');
                        data = data.substring(s + 100, e);
                        data = data.replace(/\t/g, " ").replace(/\r/g, " ").replace(/\n/g, " ").replace(/<!--(\s|\w+)*-->/g, ' ');

                        var giftlist = [];
                        var list = data.split('<a href="javascript:void(0)"');
                        for (let index = 0; index < list.length; index++) {
                            const element = list[index];
                            if (element.indexOf('<p class="activeBt">待激活＞＞</p>') > -1) {
                                var s2 = element.indexOf('toDetailPage(') + 13;
                                var e2 = element.indexOf(',\'' + mobile + '\'');

                                var str2 = element.substring(s2, e2);
                                if (!!str2.replace(/ /g, '')) {
                                    var s3 = element.indexOf('&nbsp;-&nbsp;') - 19;
                                    var e3 = s3 + 19;
                                    var str3 = element.substring(s3, e3);
                                    var o = '' + str2.replace(/'/g, '') + ',' + str3;
                                    giftlist.push(o);
                                }
                            }
                        }
                        //******解析HTML信息***********
                        let todayGet = false;
                        for (let index = 0; index < Object.keys(giftlist).length; index++) {
                            const gift = giftlist[index];
                            var thisgift = gift.split(',');
                            if (thisgift[2].split(' ')[0] == moment().format("YYYY-MM-DD")) {
                                todayGet = true;
                                if (isActive === "true") {
                                    await activegift(thisgift[0], thisgift[1], thisgift[2]);
                                } else {
                                    $.msg += '【激活】已设置不自动激活流量包\n';
                                }
                                break;
                            }
                        }
                        if (!todayGet) {
                            $.msg += '【激活】暂无可激活流量包\n';
                        }
                    }
                } catch (e) {
                    $.logErr(e, resp)
                } finally {
                    resolve();
                }
            })
        } catch (error) {
            resolve(error);
        }
    })
}

//激活当天过期的流量礼包
async function activegift(code, recordid, getDate) {
    return new Promise(resolve => {
        var option = {
            url: 'https://m.client.10010.com/myPrizeForActivity/myPrize/activationFlowPackages.htm',
            headers: {
                //"Accept-Encoding":"gzip, deflate, br",
                "Origin": "https://m.client.10010.com",
                "Connection": "keep-alive",
                "Cookie": $.cookie,
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                "Host": "m.client.10010.com",
                "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 unicom{version:iphone_c@8.0200}{systemVersion:dis}{yw_code:}",
                "Referer": "https://m.client.10010.com/myPrizeForActivity/queryPrizeDetails.htm",
                "Accept-Language": "zh-cn",
                "X-Requested-With": "XMLHttpRequest",
                "Accept": "application/json, text/javascript, */*; q=0.01"
            },
            body: 'activeCode=' + code + '&prizeRecordID=' + recordid + '&activeName=%E5%81%9A%E4%BB%BB%E5%8A%A1%E9%A2%86%E5%A5%96%E5%93%81'
        };

        $.post(option, async (err, resp, data) => {
            try {
                if (err) {
                    console.log(`${$.name} API请求失败，请检查网路重试`);
                    console.log(`${JSON.stringify(err)}`)
                } else {
                    data = JSON.parse(data);
                    if (data.status == "200") {
                        $.msg += `【激活】${getDate}获取的流量包已激活成功，实际以短信或手机营业厅查询为准\n`;
                    } else {
                        $.msg += `【激活】${getDate}获取的流量包激活失败\n`;
                    }
                }
            } catch (e) {
                $.logErr(e, resp)
            } finally {
                resolve();
            }
        })
    })
}
//prettier-ignore
function Env(t, e) { "undefined" != typeof process && JSON.stringify(process.env).indexOf("GITHUB") > -1 && process.exit(0); class s { constructor(t) { this.env = t } send(t, e = "GET") { t = "string" == typeof t ? { url: t } : t; let s = this.get; return "POST" === e && (s = this.post), new Promise((e, i) => { s.call(this, t, (t, s, r) => { t ? i(t) : e(s) }) }) } get(t) { return this.send.call(this.env, t) } post(t) { return this.send.call(this.env, t, "POST") } } return new class { constructor(t, e) { this.name = t, this.http = new s(this), this.data = null, this.dataFile = "box.dat", this.logs = [], this.isMute = !1, this.isNeedRewrite = !1, this.logSeparator = "\n", this.startTime = (new Date).getTime(), Object.assign(this, e), this.log("", `🔔${this.name}, 开始!`) } isNode() { return "undefined" != typeof module && !!module.exports } isQuanX() { return "undefined" != typeof $task } isSurge() { return "undefined" != typeof $httpClient && "undefined" == typeof $loon } isLoon() { return "undefined" != typeof $loon } toObj(t, e = null) { try { return JSON.parse(t) } catch { return e } } toStr(t, e = null) { try { return JSON.stringify(t) } catch { return e } } getjson(t, e) { let s = e; const i = this.getdata(t); if (i) try { s = JSON.parse(this.getdata(t)) } catch { } return s } setjson(t, e) { try { return this.setdata(JSON.stringify(t), e) } catch { return !1 } } getScript(t) { return new Promise(e => { this.get({ url: t }, (t, s, i) => e(i)) }) } runScript(t, e) { return new Promise(s => { let i = this.getdata("@chavy_boxjs_userCfgs.httpapi"); i = i ? i.replace(/\n/g, "").trim() : i; let r = this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout"); r = r ? 1 * r : 20, r = e && e.timeout ? e.timeout : r; const [o, h] = i.split("@"), n = { url: `http://${h}/v1/scripting/evaluate`, body: { script_text: t, mock_type: "cron", timeout: r }, headers: { "X-Key": o, Accept: "*/*" } }; this.post(n, (t, e, i) => s(i)) }).catch(t => this.logErr(t)) } loaddata() { if (!this.isNode()) return {}; { this.fs = this.fs ? this.fs : require("fs"), this.path = this.path ? this.path : require("path"); const t = this.path.resolve(this.dataFile), e = this.path.resolve(process.cwd(), this.dataFile), s = this.fs.existsSync(t), i = !s && this.fs.existsSync(e); if (!s && !i) return {}; { const i = s ? t : e; try { return JSON.parse(this.fs.readFileSync(i)) } catch (t) { return {} } } } } writedata() { if (this.isNode()) { this.fs = this.fs ? this.fs : require("fs"), this.path = this.path ? this.path : require("path"); const t = this.path.resolve(this.dataFile), e = this.path.resolve(process.cwd(), this.dataFile), s = this.fs.existsSync(t), i = !s && this.fs.existsSync(e), r = JSON.stringify(this.data); s ? this.fs.writeFileSync(t, r) : i ? this.fs.writeFileSync(e, r) : this.fs.writeFileSync(t, r) } } lodash_get(t, e, s) { const i = e.replace(/\[(\d+)\]/g, ".$1").split("."); let r = t; for (const t of i) if (r = Object(r)[t], void 0 === r) return s; return r } lodash_set(t, e, s) { return Object(t) !== t ? t : (Array.isArray(e) || (e = e.toString().match(/[^.[\]]+/g) || []), e.slice(0, -1).reduce((t, s, i) => Object(t[s]) === t[s] ? t[s] : t[s] = Math.abs(e[i + 1]) >> 0 == +e[i + 1] ? [] : {}, t)[e[e.length - 1]] = s, t) } getdata(t) { let e = this.getval(t); if (/^@/.test(t)) { const [, s, i] = /^@(.*?)\.(.*?)$/.exec(t), r = s ? this.getval(s) : ""; if (r) try { const t = JSON.parse(r); e = t ? this.lodash_get(t, i, "") : e } catch (t) { e = "" } } return e } setdata(t, e) { let s = !1; if (/^@/.test(e)) { const [, i, r] = /^@(.*?)\.(.*?)$/.exec(e), o = this.getval(i), h = i ? "null" === o ? null : o || "{}" : "{}"; try { const e = JSON.parse(h); this.lodash_set(e, r, t), s = this.setval(JSON.stringify(e), i) } catch (e) { const o = {}; this.lodash_set(o, r, t), s = this.setval(JSON.stringify(o), i) } } else s = this.setval(t, e); return s } getval(t) { return this.isSurge() || this.isLoon() ? $persistentStore.read(t) : this.isQuanX() ? $prefs.valueForKey(t) : this.isNode() ? (this.data = this.loaddata(), this.data[t]) : this.data && this.data[t] || null } setval(t, e) { return this.isSurge() || this.isLoon() ? $persistentStore.write(t, e) : this.isQuanX() ? $prefs.setValueForKey(t, e) : this.isNode() ? (this.data = this.loaddata(), this.data[e] = t, this.writedata(), !0) : this.data && this.data[e] || null } initGotEnv(t) { this.got = this.got ? this.got : require("got"), this.cktough = this.cktough ? this.cktough : require("tough-cookie"), this.ckjar = this.ckjar ? this.ckjar : new this.cktough.CookieJar, t && (t.headers = t.headers ? t.headers : {}, void 0 === t.headers.Cookie && void 0 === t.cookieJar && (t.cookieJar = this.ckjar)) } get(t, e = (() => { })) { t.headers && (delete t.headers["Content-Type"], delete t.headers["Content-Length"]), this.isSurge() || this.isLoon() ? (this.isSurge() && this.isNeedRewrite && (t.headers = t.headers || {}, Object.assign(t.headers, { "X-Surge-Skip-Scripting": !1 })), $httpClient.get(t, (t, s, i) => { !t && s && (s.body = i, s.statusCode = s.status), e(t, s, i) })) : this.isQuanX() ? (this.isNeedRewrite && (t.opts = t.opts || {}, Object.assign(t.opts, { hints: !1 })), $task.fetch(t).then(t => { const { statusCode: s, statusCode: i, headers: r, body: o } = t; e(null, { status: s, statusCode: i, headers: r, body: o }, o) }, t => e(t))) : this.isNode() && (this.initGotEnv(t), this.got(t).on("redirect", (t, e) => { try { if (t.headers["set-cookie"]) { const s = t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString(); s && this.ckjar.setCookieSync(s, null), e.cookieJar = this.ckjar } } catch (t) { this.logErr(t) } }).then(t => { const { statusCode: s, statusCode: i, headers: r, body: o } = t; e(null, { status: s, statusCode: i, headers: r, body: o }, o) }, t => { const { message: s, response: i } = t; e(s, i, i && i.body) })) } post(t, e = (() => { })) { if (t.body && t.headers && !t.headers["Content-Type"] && (t.headers["Content-Type"] = "application/x-www-form-urlencoded"), t.headers && delete t.headers["Content-Length"], this.isSurge() || this.isLoon()) this.isSurge() && this.isNeedRewrite && (t.headers = t.headers || {}, Object.assign(t.headers, { "X-Surge-Skip-Scripting": !1 })), $httpClient.post(t, (t, s, i) => { !t && s && (s.body = i, s.statusCode = s.status), e(t, s, i) }); else if (this.isQuanX()) t.method = "POST", this.isNeedRewrite && (t.opts = t.opts || {}, Object.assign(t.opts, { hints: !1 })), $task.fetch(t).then(t => { const { statusCode: s, statusCode: i, headers: r, body: o } = t; e(null, { status: s, statusCode: i, headers: r, body: o }, o) }, t => e(t)); else if (this.isNode()) { this.initGotEnv(t); const { url: s, ...i } = t; this.got.post(s, i).then(t => { const { statusCode: s, statusCode: i, headers: r, body: o } = t; e(null, { status: s, statusCode: i, headers: r, body: o }, o) }, t => { const { message: s, response: i } = t; e(s, i, i && i.body) }) } } time(t, e = null) { const s = e ? new Date(e) : new Date; let i = { "M+": s.getMonth() + 1, "d+": s.getDate(), "H+": s.getHours(), "m+": s.getMinutes(), "s+": s.getSeconds(), "q+": Math.floor((s.getMonth() + 3) / 3), S: s.getMilliseconds() }; /(y+)/.test(t) && (t = t.replace(RegExp.$1, (s.getFullYear() + "").substr(4 - RegExp.$1.length))); for (let e in i) new RegExp("(" + e + ")").test(t) && (t = t.replace(RegExp.$1, 1 == RegExp.$1.length ? i[e] : ("00" + i[e]).substr(("" + i[e]).length))); return t } msg(e = t, s = "", i = "", r) { const o = t => { if (!t) return t; if ("string" == typeof t) return this.isLoon() ? t : this.isQuanX() ? { "open-url": t } : this.isSurge() ? { url: t } : void 0; if ("object" == typeof t) { if (this.isLoon()) { let e = t.openUrl || t.url || t["open-url"], s = t.mediaUrl || t["media-url"]; return { openUrl: e, mediaUrl: s } } if (this.isQuanX()) { let e = t["open-url"] || t.url || t.openUrl, s = t["media-url"] || t.mediaUrl; return { "open-url": e, "media-url": s } } if (this.isSurge()) { let e = t.url || t.openUrl || t["open-url"]; return { url: e } } } }; if (this.isMute || (this.isSurge() || this.isLoon() ? $notification.post(e, s, i, o(r)) : this.isQuanX() && $notify(e, s, i, o(r))), !this.isMuteLog) { let t = ["", "==============📣系统通知📣=============="]; t.push(e), s && t.push(s), i && t.push(i), console.log(t.join("\n")), this.logs = this.logs.concat(t) } } log(...t) { t.length > 0 && (this.logs = [...this.logs, ...t]), console.log(t.join(this.logSeparator)) } logErr(t, e) { const s = !this.isSurge() && !this.isQuanX() && !this.isLoon(); s ? this.log("", `❗️${this.name}, 错误!`, t.stack) : this.log("", `❗️${this.name}, 错误!`, t) } wait(t) { return new Promise(e => setTimeout(e, t)) } done(t = {}) { const e = (new Date).getTime(), s = (e - this.startTime) / 1e3; this.log("", `🔔${this.name}, 结束! 🕛 ${s} 秒`), this.log(), (this.isSurge() || this.isQuanX() || this.isLoon()) && $done(t) } }(t, e) }